package game

import (
	"context"
	"github.com/tianjigames/fairy/constants"
	"github.com/tianjigames/fairy/manager"
	"github.com/tianjigames/fairy/model"
	"github.com/tianjigames/fairy/pojo"
	"github.com/tianjigames/fairy/protos"
	"github.com/topfreegames/pitaya"
	"github.com/topfreegames/pitaya/component"
	constants2 "github.com/topfreegames/pitaya/constants"
	"github.com/topfreegames/pitaya/logger"
	"github.com/topfreegames/pitaya/util"
)

type GameHandler struct {
	component.Base
}

func NewGameHandler() *GameHandler {
	return &GameHandler{}
}

/**
初始化游戏
 */
func (p *GameHandler) InitGame(ctx context.Context,req *protos.CGInitGame) (*protos.GCInitGameRet,error) {
	s := pitaya.GetSessionFromCtx(ctx)
	logger.Log.Debugf("[GameHandler] InitGame PlayerId:%d is connecting",req.PlayerId)

	daemon := pitaya.ThreadPool.GetThread(constants.DaemonThread).(*manager.DaemonThread)
	if daemon != nil && daemon.IsAlive() {
		pUser := daemon.GetFromDisConnectPlayerList(s.UID())
		if pUser != nil && pUser.MGameState == model.PlayerLoginNormal {//等待玩家重新连接
			return &protos.GCInitGameRet{
				RetCode: constants.InitGameWaitConnect,
			},nil
		}
	}

	playerAuthRet := &protos.WGPlayerAuthRet{}
	err := pitaya.RPC(ctx, constants.GWPlayerAuthRoute,playerAuthRet,&protos.GWPlayerAuth{
		AccountId: req.AccountId,
		PlayerId:  req.PlayerId,
		Ticket:    req.Ticket,
		AppId:     req.AppId,
		ServerId:  pitaya.GetServerID(),
	})

	if err != nil {
		logger.Log.Errorf("InitGame failed,error=%s",err.Error())
		return nil,err
	}

	retCode := playerAuthRet.GetRetCode()
	if retCode != constants.InitGameAuthSuccess {
		return &protos.GCInitGameRet{
			RetCode:       retCode,
		},nil
	}

	//处理认证成功逻辑
	inTh := pitaya.ThreadPool.GetThread(constants.IncomingThread)
	if inTh != nil && util.GetGoroutineID() != inTh.ID() {
		//交给incomingThread进行处理
		inTh.(*manager.IncomingThread).AddMessage(manager.InitGameRoute,ctx,req)
		return nil,constants2.ErrReturnNil
	}

	//当前线程处理逻辑
	if playerAuthRet.RetCode != constants.InitGameAuthSuccess {
		return &protos.GCInitGameRet{RetCode: playerAuthRet.RetCode},nil
	}

	//秘钥正确 处理初始化游戏逻辑
	pDataMsg := playerAuthRet.PlayerData
	playerId := int(pDataMsg.PlayerId)
	var playerObj *model.PlayerObject
	if daemon != nil {
		playerObj = daemon.RemoveAndGetDisConnectPlayer(pitaya.GetSessionFromCtx(ctx).UID(),playerId)
	}


	resp := &protos.GWRetForceLogout{}
	resp.AccountId = pDataMsg.AccountId
	resp.AppId = pDataMsg.AppId

	var pData *pojo.PlayerData
	if playerObj == nil {
		//解析playerData数据
		pData = pojo.MakePlayerData(pDataMsg)
		if pData == nil {
			err = s.Push(constants.CGInitGameRoute,&protos.GCInitGameRet{RetCode: constants.InitGameFailError})
			if err != nil {
				logger.Log.Errorf("[InitGame] failed,accountId=%d,error:%s",pDataMsg.AccountId,err.Error())
				return nil,err
			}

			resp.Reason = constants.WorldKickUserOffline
			//踢出玩家下线
			err = pitaya.RPC(ctx,constants.GWRetForceLogout,&protos.WGRetForceLogoutrRet{},resp)
			if err != nil {
				logger.Log.Errorf("[InitGame] failed,accountId=%d,error:%s",pDataMsg.AccountId,err.Error())
				return nil,err
			}
			return nil,constants2.ErrReturnNil
		}

		playerObj,err = manager.PlayerManager.NewPlayerObject(pData)
		if err != nil {
			logger.Log.Errorf("[InitGame] failed,accountId=%d,error:%s",pDataMsg.AccountId,err.Error())
			return nil,err
		}

		isNewPlayer := false
		if pData.Rolelevel <= 1 {
			isNewPlayer = true
		}
		playerObj.MBFirstLoginGame = isNewPlayer
		playerObj.SessionId = pitaya.GetSessionFromCtx(ctx).UID()
		//加载玩家其他数据

	}else{
		pData = playerObj.PlayerData
	}



	return nil,constants2.ErrReturnNil
}